package com.avecsys.quotemanager.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.icesoft.faces.context.effects.JavascriptContext;

public class BaseValidator implements Validator {
	public void validate(FacesContext facesContext, UIComponent uIComponent,
			Object usrArgument) throws ValidatorException {
		FacesMessage message = validateFieldValue(facesContext, uIComponent,
				usrArgument);
		if (message != null && message.getSummary() != null
				&& message.getSummary().trim().length() > 0) {
			setFocus(facesContext, uIComponent, message);
			throw new ValidatorException(message);
		}
	}

	/**
	 * Should be overiden by all the custom validation classes which extends
	 * BaseValidator
	 * 
	 * @param facesContext
	 * @param uIComponent
	 * @param object
	 * @return
	 * @throws ValidatorException
	 */
	public FacesMessage validateFieldValue(FacesContext facesContext,
			UIComponent uIComponent, Object object) throws ValidatorException {
		return null;
	}

	public void setFocus(FacesContext facesContext, UIComponent uIComponent,
			FacesMessage message) {
		JavascriptContext
				.addJavascriptCall(
						FacesContext.getCurrentInstance(),
						" document.getElementById('"
								+ uIComponent.getClientId(facesContext)
								+ "').focus();");
	}
}
